<?php header('Access-Control-Allow-Origin: *'); ?>
<?php

date_default_timezone_set('America/Chicago');
include_once 'class_db_loader.php';
include_once 'loadTemplate.php';
include_once('Mail.php');
include_once('Mail/mime.php');

class core {

    /**
     *
     * @var ezSQL_mysql
     */
    var $db;
    var $rand_key;
    var $limit = 10;

    #============================================================
    # Construct
    #============================================================

    function __construct() {
        $dbConnection = new db();
        $this->db = $dbConnection->connect('iclick', 'iclick2013', 'wedding_reminder', '');
    }

    protected function _preDataForInsert($data, &$fields, &$values) {
        foreach ($data as $k => $v) {
            $fields[] = "`" . $k . "`";
            $values[] = "'" . $this->db->escape($v) . "'";
        }
    }

    protected function _preDataForUpdate($data, &$fields) {
        foreach ($data as $k => $v) {
            $fields[] = "`{$k}` = '{$this->db->escape($v)}'";
        }
    }

    protected function _response($response = null) {
        echo $response;
        die;
    }

    protected function _JSONResponse($response = null) {
        echo json_encode($response);
        die;
    }

    protected function _cleanEmail($email) {
        $email = preg_replace('/[^a-zA-Z0-9\@\.\-\_]/', '', $email);

        if ($this->_validateEmail($email)) {
            return $email;
        } else {
            return false;
        }
    }

    protected function _validateEmail($email) {
        if (!$email) {
            return false;
        }

        if (substr_count($email, '@') != 1 || substr_count($email, ' ') > 0) {
            return false;
        }

        if (!preg_match("/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]+|[0-9]{1,4})(\]?)$/", $email)) {
            return false;
        }

        return true;
    }

    protected function checkStateID($stateID) {
        $result = $this->db->get_row("SELECT id FROM states WHERE id='" . $stateID . "'");
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    protected function checkEventID($eventID) {
        $result = $this->db->get_row("SELECT event_id FROM events WHERE event_id=" . $eventID);

        if ($result) {
            return true;
        } else {
            return false;
        }
    }
    public function checkExistGuest($fb_guest_id, $user_id) {
        $result = $this->db->get_row("SELECT guest_id FROM guests WHERE fbid='" . $fb_guest_id."' AND user_id=".$user_id);

        if ($result) {
            return true;
        } else {
            return false;
        }
    }
    protected function checkProfileID($profileID) {
        $query = "SELECT * FROM user_device WHERE profile_id=" . $profileID;

        $result = $this->db->get_row($query);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    protected function checkOldPassword($oldPass, $user_id) {
        $query = "SELECT id FROM users 
    	WHERE password='" . md5($oldPass) . "' AND id=" . $user_id;
        $result = $this->db->get_row($query);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    protected function getUserIDByProfileID($profileID) {
        $query = "SELECT user_id FROM user_device
    	WHERE user_device.profile_id=" . $profileID;
        $result = $this->db->get_row($query);
        if ($result) {
            return $result->user_id;
        } else {
            return false;
        }
    }

    protected function getDeviceIDByProfileID($profile_id) {
        $query = "SELECT device_id FROM user_device
    	WHERE user_device.profile_id=" . $profile_id;
        $result = $this->db->get_row($query);
        if ($result) {
            return $result->device_id;
        } else {
            return false;
        }
    }

    protected function getUserInfoByProfileID($profile_id) {
        $query = "SELECT * FROM users, user_device WHERE users.id= user_device.user_id AND user_device.profile_id=" . $profile_id;
        $result = $this->db->get_row($query);
        if ($result) {
            return $result;
        } else {
            return false;
        }
    }

    public function send_mail($to, $subject, $content, $from = SMTP_FROM_EMAIL, $cc = '') {

        $host = "email-smtp.us-east-1.amazonaws.com";
        $username = "AKIAJDV267TOVVH6A57Q";
        $password = "AnHeFy0XJk4uNNYY/Wt0b5HKIWz9Hqp95YSZFrZ92/jH";

        $recipients = array();
        $recipients[] = $to;

        $headers = array('From' => 'Wedding Helper <no-reply@iclickapps.com>',
            'To' => $to,
            'Subject' => $subject);

        $smtp = Mail::factory('smtp', array('host' => $host,
                    'auth' => true,
                    'username' => $username,
                    'password' => $password));

        $message = new Mail_mime();
        $message->setHTMLBody(strtr(stripslashes($content), array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')));
        $body = $message->get();
        $headers = $message->headers($headers);

        $result = $smtp->send($recipients, $headers, $body);

        if ($result != 1) {
            return false;
        }
        return true;
    }

    public function changeDateToSaveMySql($date, $timezone) {
        $timezone_default = "America/Chicago";

        $date_input = DateTime::createFromFormat('Y-m-d H:i:s T', $date . ' ' . $timezone);

        $timezone_format = new DateTimeZone($timezone_default);

        $date_input->setTimeZone($timezone_format);

        return $date_input->format('Y-m-d H:i:s');
    }

    

    function SanitizeForSQL($str) {
        if (function_exists("mysql_real_escape_string")) {
            $ret_str = mysql_real_escape_string($str);
        } else {
            $ret_str = addslashes($str);
        }
        return $ret_str;
    }
    public static function activeUserFromCode($code) {
        $core = new core();
        $code = $core->db->escape($code);
        $query = "UPDATE users
			SET active=1,confirmation_code=''
			WHERE confirmation_code='" . $code . "';";
        if ($core->db->query($query)) {
            return true;
        } else {
            return false;
        }
    }
    function GetAbsoluteURLFolder() {
        $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
        $scriptFolder .= $_SERVER['HTTP_HOST'];
        return $scriptFolder;
    }
   

}

?>